from django.shortcuts import render
from app import models
def login_view(request):
    if request.method =="POST":
        user_name=request.POST.get('user_name','')
        pass_word=request.POST.get('pwd','')
        user=models.User.objects.get(user_name=user_name,pwd=pass_word)
        if user:
            if pass_word==user.pwd:
                request.session['IS_LOGIN']=True
                request.session['user_name']=user_name
                request.session['user_id']=user.id
                return render(request,'index.html',{'user_name':user_name})
            else:
                return render(request,'login.html',{'error:用户名或密码错误!'})
        else:
            return render(request, 'login.html', {'error:用户名不存在！'})
    elif request.method=="GET":
        return render(request,'login.html')
    else:
        return render(request,'login.html')
def login_out(request):
    request.session.flush()
    return render(request,'login.html')

def register_view(requset):
    if requset.method=="GET":
        return render(requset,'register.html')
    elif requset.method=="POST":
        user_name=requset.POST.get('user_name','')
        pass_word_1=requset.POST.get('pwd','')
        pass_word_2 = requset.POST.get('cpwd', '')
        phone=requset.POST.get('phone','')
        if models.User.objects.filter(user_name=user_name):
            return render(requset,'register.html',{'error':'用户已存在'})
        if pass_word_1!=pass_word_2:
            return render(requset,'register.html',{'error':'两次密码请输入一致'})
        user=models.User()
        user.user_name=user_name
        user.pwd=pass_word_1
        user.phone=phone
        user.save()
        return render(requset,'login.html')
    else:
        return render(requset,'register.html')
def index_view(requset):
    return render(requset, 'register.html')
# Create your views here.
def index(request):
    if request.method=="GET":
        goods_type=models.Type.objects.all()
    goods_dict={}
    for type in goods_type:
        goods_list=models.Goods.object.filter(type__id =type.id)[:4]
        goods_dict[type.type_name]=goods_list
    print(goods_dict)
    return render(request,"index.html",{"goods_list":goods_dict,"goods_type":goods_type})
def index_view(request):
    good_list=models.Goods.object.all()
    return render(request,'index.html',{"goods_list":good_list,'user_name': request.session.get('user_name',None) })
def goodDetail(requset,id):
    good_detail=models.Goods.object.get(id=id)
    return render(requset,'detail-html',{"good": good_detail,'user_name': requset.session.get('user_name',None)})